//
//  TestRootViewController.m
//  Founder_study
//
//  Created by hongbao.cui on 14-8-29.
//  Copyright (c) 2014年 com.founder. All rights reserved.
//

#import "TestRootViewController.h"
#import "SynExericisesPaperData.h"
#import "Sqlite.h"
#import "ZipArchive.h"
#import "SwipeView.h"
#import "ApplicationUtils.h"
#import "PaperListView.h"
#import "XingAndLabel_UIView.h"
#import "ISMutileButton.h"
#import "ApplicationUtils.h"
#import "CaseQuestionView.h"
#import "ResultViewController.h"
#import "HBListTableView.h"
#import "HBTableViewFooterView.h"
#import "DraftViewController.h"
//#import "SimpleFooterView.h"
//#import "FMTxtPhotoViewController.h"
#import "FMSNetWorkModule.h"
#import <AVFoundation/AVFoundation.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "HBSimpleTableViewCell.h"
#import "FMReachability.h"
@interface TestRootViewController ()<HBListTableViewDelegate,HBTableViewFooterViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>{
    UIImage *editeImage;
     UIBackgroundTaskIdentifier backgroundTask; //用来保存后台运行任务的标示符
}
@property(nonatomic,weak)UIButton  *answerBtn;
@property(nonatomic,strong)NSMutableArray *homeworkArray;
@end

@implementation TestRootViewController
@synthesize answerArray;
@synthesize paperArray;
@synthesize supportedOrientationsMask;
@synthesize homeworkArray;
-(NSString *)pngFilePath{
    NSString *strPath = [NSString stringWithFormat:@"%@/image",[self.urlDict objectForKey:@"paperID"]];
    NSString *path0 = [FMPAPERSAVE_PATH stringByAppendingPathComponent:strPath];
    NSString *fileName = [NSString stringWithFormat:@"%@_%ld.png",[self.urlDict objectForKey:@"paperID"],(long)_currentPage];
    NSString *pngPath = [path0 stringByAppendingPathComponent:fileName];
    if ([ApplicationUtils isFileExitsAtPath:path0]) {
        FMSCHBLog(@"创建目录成功");
    }else{
        FMSCHBLog(@"目录已存在");
    }
    return pngPath;
}
-(NSString *)jsonFilePath{
    NSString *strPath = [NSString stringWithFormat:@"%@",[self.urlDict objectForKey:@"paperID"]];
    NSString *path0 = [FMPAPERSAVE_PATH stringByAppendingPathComponent:strPath];
    NSString *pngPath = [path0 stringByAppendingPathComponent:@"answer.json"];
    if ([ApplicationUtils isFileExitsAtPath:path0]) {
        FMSCHBLog(@"创建目录成功");
    }else{
        FMSCHBLog(@"目录已存在");
    }
    return pngPath;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
//试卷试图的更新
-(void)initTestView:(NSString *)title{
//    NSString *paperTitleAndCount = [NSString stringWithFormat:@"%@ 共%lu题",title,(unsigned long)[self.paperArray count]];
    NSString *paperTitleAndCount = [NSString stringWithFormat:@"%@",title];
    CGSize size = [paperTitleAndCount sizeWithFont:[UIFont systemFontOfSize:13.0] constrainedToSize:CGSizeMake(FMSCREENWIDTH-85, 35) lineBreakMode:NSLineBreakByWordWrapping];
    dispatch_async(dispatch_get_main_queue(), ^{
        [titleLabel setNumberOfLines:0];
        [titleLabel setLineBreakMode:NSLineBreakByWordWrapping];
        [titleLabel setFont:[UIFont systemFontOfSize:13.0]];
        [titleLabel setText:paperTitleAndCount];
        [titleLabel setFrame:CGRectMake(10, (MAX(titleLabel.frame.size.height, 30)-size.height)/2, size.width, size.height)];
        [headerBg setFrame:CGRectMake(0, 0, FMSCREENWIDTH, MAX(titleLabel.frame.size.height, 30))];
        if ([self.paperArray count]>0) {
            [_swipeView reloadData];
        }
        [ApplicationUtils promptRemove];
    });
    NSString *titleAndCount = [NSString stringWithFormat:@"%02ld/%02lu",_currentPage+1,(unsigned long)[self.paperArray count]];
    [totalLabel setText:titleAndCount];
}
-(void)showTestPaper{
    if (IS_STUDY) {
        BOOL isReachable = [[FMReachability FMReachabilityWithHostname:@"www.baidu.com"] isReachable];
        if (isReachable) {
            [self initAnswerData];
        }else{
            NSString *paperId = [NSString stringWithFormat:@"%@",[_urlDict objectForKey:@"paperID"]];
            NSMutableArray *array_afterSave = [Sqlite selectTestQuestion:paperId];
            if (!self.paperArray) {
                self.paperArray = [NSMutableArray arrayWithCapacity:1];
            }
            [self.paperArray addObjectsFromArray:array_afterSave];//存为全局，以后使用
            paper_title = nil;
            paper_score = nil;
            paper_time = nil;
            if ([self.paperArray count]>0) {
                paper_title = [[self.paperArray objectAtIndex:0] objectForKey:@"paper_title"];
                paper_score = [[self.paperArray objectAtIndex:0] objectForKey:@"paper_score"];
                paper_time = [[self.paperArray objectAtIndex:0] objectForKey:@"paper_time"];
            }else{
                FMSCHBLog(@"----cuihongbao-----加载数据失败!");
                [ApplicationUtils promptRemove];
                return;
            }
            [self initTestView:paper_title];
        }
    }else{//移动学习
        NSString *paperId = [NSString stringWithFormat:@"%@",[_urlDict objectForKey:@"paperID"]];
        NSMutableArray *array_afterSave = [Sqlite selectTestQuestion:paperId];
        if (!self.paperArray) {
            self.paperArray = [NSMutableArray arrayWithCapacity:1];
        }
        [self.paperArray removeAllObjects];
        [self.paperArray addObjectsFromArray:array_afterSave];//存为全局，以后使用
        paper_title = nil;
        paper_score = nil;
        paper_time = nil;
        if ([self.paperArray count]>0) {
            paper_title = [[self.paperArray objectAtIndex:0] objectForKey:@"paper_title"];
            paper_score = [[self.paperArray objectAtIndex:0] objectForKey:@"paper_score"];
            paper_time = [[self.paperArray objectAtIndex:0] objectForKey:@"paper_time"];
        }else{
            FMSCHBLog(@"----cuihongbao-----加载数据失败!");
            [ApplicationUtils promptRemove];
            return;
        }
        //计算得分
        for (NSDictionary *dict in self.paperArray) {
            NSString *user_Answer = [dict objectForKey:@"user_answer"];
            NSString *answer = [dict objectForKey:@"answer"];
            NSString *score = [dict objectForKey:@"score"];
            if ([user_Answer isEqualToString:answer]) {
                Sum = Sum+1*[score intValue];
            }
        }
        [self initTestView:paper_title];
    }
}
-(NSString *)converToJson:(id)object{
    NSError *error;
    if ([NSJSONSerialization isValidJSONObject:object]) {
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&error];
        NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        return json;
    }
    FMSCHBLog(@"error------jsonObject is not  Valid!");
    return nil;
}
-(void)submitHomeWork:(NSString *)Typestatus{
    [ApplicationUtils promptRotateWithViewTitle:@"请稍候..." showView:self.view];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSArray *array =[Sqlite selectTestQuestionWhenNOAnswer:[self.urlDict objectForKey:@"paperID"]];
        for (NSInteger atIndex = 0; atIndex<[array count]; atIndex++) {
            NSDictionary *dataDict =  [array objectAtIndex:atIndex];
            NSMutableDictionary *answerDict = [NSMutableDictionary dictionaryWithCapacity:1.0];
            NSString *parentId = [dataDict objectForKey:@"parent_id"];
            [answerDict setObject:parentId forKey:@"parentId"];
            NSString *qstId = [dataDict objectForKey:@"qstId"];
            [answerDict setObject:qstId forKey:@"qstId"];
            NSString *subCount = [dataDict objectForKey:@"has_sub"];
            [answerDict setObject:subCount forKey:@"subCount"];
            NSString *tqId = [dataDict objectForKey:@"tq_id"];
            [answerDict setObject:tqId forKey:@"tqId"];
            NSString *userAnswer = [dataDict objectForKey:@"user_answer"];
            if (!userAnswer&&[userAnswer isEqualToString:@"(null)"]) {
                userAnswer = @"";
            }
            [answerDict setObject:userAnswer forKey:@"userAnswer"];
            NSString *standardAnswer = [dataDict objectForKey:@"answer"];
            [answerDict setObject:standardAnswer forKey:@"standardAnswer"];
            NSString *viewTypeId = [dataDict objectForKey:@"qtype"];
            [answerDict setObject:viewTypeId forKey:@"viewTypeId"];
            NSString *userAnswerImage = [dataDict objectForKey:@"userAnswerImage"];
            if (userAnswerImage==nil) {
                userAnswerImage = @"0";
            }
            [answerDict setObject:userAnswerImage forKey:@"userAnswerImage"];
            NSString *resultFlag = nil;
            if ([userAnswer isEqualToString:standardAnswer]) {
                resultFlag = @"1";
            }else{
                if ([viewTypeId isEqualToString:@"0"]) {
                    resultFlag = @"";
                }else{
                    resultFlag = @"0";
                }
            }
            [answerDict setObject:resultFlag forKey:@"resultFlag"];
            NSString *userScoreRate = @"0%";
            [answerDict setObject:userScoreRate forKey:@"userScoreRate"];
            [self.homeworkArray addObject:answerDict];
        }
        FMSCHBLog(@"user_time------->%@",self.user_time);
//        NSArray *timeArray = [user_time componentsSeparatedByString:@":"];
//        NSString *timeStr = nil;
//        if ([timeArray count]==3) {
//            NSInteger time = [[timeArray objectAtIndex:0] integerValue]*60*60+[[timeArray objectAtIndex:1] integerValue]*60+[[timeArray objectAtIndex:2] integerValue];
//            timeStr = [NSString stringWithFormat:@"%ld",(long)time];
//        }else{
//            timeStr = @"0";
//        }
        //保存作业
        NSString *homeworkid = [NSString stringWithFormat:@"%@",[self.urlDict objectForKey:@"paperID"]];
        NSString *authToken = [self.urlDict objectForKey:@"authToken"];
        NSString *userId =  [self.urlDict objectForKey:@"userId"];
        NSMutableDictionary *pargamDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:userId,@"userId",homeworkid,@"resultId",authToken,@"authToken",Typestatus,@"status",self.user_time,@"usedTime", nil];
        NSString *json =[self converToJson:self.homeworkArray];
        FMSCHBLog(@"json data:%@",json);
        NSString *jsonPath = [self jsonFilePath];
        NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
        [jsonData writeToFile:jsonPath atomically:YES];
        
        //    [pargamDict setObject:json forKey:@"resultContent"];
        //    NSString *postJson =[self converToJson:pargamDict];
        FMSCHBLog(@"postJson data:%@",pargamDict);
        NSString *zipFileName = [NSString stringWithFormat:@"%@/%@.zip",FMPAPERSAVE_PATH,@"answer"];
        ZipArchive* zipFile = [[ZipArchive alloc] init];
        [zipFile CreateZipFile2:zipFileName];
        BOOL ret = [zipFile addFileToZip:jsonPath newname:@"answer.json"];
        NSString *strPath = [NSString stringWithFormat:@"%@/image",[self.urlDict objectForKey:@"paperID"]];//图片路径
        NSString *path0 = [FMPAPERSAVE_PATH stringByAppendingPathComponent:strPath];
        NSFileManager *fileMgr = [NSFileManager defaultManager];
        NSError *error = nil;
        NSArray *dataArray = [fileMgr contentsOfDirectoryAtPath:path0 error:&error];
        if ([dataArray count]>0) {
            for (NSString *fileName in dataArray) {
                NSString *filePath = [NSString stringWithFormat:@"%@/%@/%@",FMPAPERSAVE_PATH,strPath,fileName];
                NSString *name = [NSString stringWithFormat:@"image/%@",fileName];
                ret = [zipFile addFileToZip:filePath newname:name];
            }
        }else{
            
        }
        [zipFile CloseZipFile2];
        [pargamDict setObject:zipFileName forKey:@"resultContent"];
        NSString  *plistPath = [[NSBundle mainBundle] pathForResource:@"Config" ofType:@"plist"];
        NSMutableDictionary *dataDict = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
        NSString *ip_host = [dataDict objectForKey:@"ip_host"];
        NSString *ip_root = [dataDict objectForKey:@"ip_root"];
        NSString *ip_path = [NSString stringWithFormat:@"%@submitHomeworkResult.do",ip_root];
//        NSString *ip_path = @"/tqmsapp/app/homework/api/submitHomeworkResult.do";
        [[FMSNetWorkModule sharedInstance] postRequestDataWithMethod:pargamDict withURLPath:ip_path showHintView:nil completionCB:^(id result) {
            FMSCHBLog(@"---------------result-------------%@",result);
            NSDictionary *dict = (NSDictionary *)result;
            NSString *success = [dict objectForKey:@"status"];
            if ([success isEqualToString:@"SUCCESS"]) {
                if ([Typestatus isEqualToString:@"2"]) {
                    NSUserDefaults *standard = [NSUserDefaults standardUserDefaults];
                    NSString *paperIDWithName =[NSString stringWithFormat:@"%@_%@",[self.urlDict objectForKey:@"paperID"],@"userName"];
                    [standard setObject:@"0" forKey:paperIDWithName];
                }
                if (![isReset isEqualToString:@"3"]) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"TestRootViewController" object:nil];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        //删除多余文件
                        NSString *strPath = [NSString stringWithFormat:@"%@/%@",FMPAPERSAVE_PATH,homeworkid];
                        [ApplicationUtils deleteExitsFile:strPath];
                        [ApplicationUtils promptRemove];
                        // 更新界面
                        [self.navigationController dismissViewControllerAnimated:YES completion:^{
                        }];
                    });
                }else{
                    [self showTestPaper];
                }
            }
        } errorCB:^(NSString *error) {
            FMSCHBLog(@"---------------error-------------%@",error);
            dispatch_async(dispatch_get_main_queue(), ^{
                [ApplicationUtils promptRemove];
                [ApplicationUtils showAlertMSG:@"同步失败请重新保存"];
            });
        }];
    });
}
#pragma mark UIAlertViewDelegate
#pragma -
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:
        {
            if (alertView.tag == 1) {
                
            }
            if (alertView.tag == 2) {
                //更新做题ueser_answer =@""; 取消做题记录
                NSUserDefaults *standard = [NSUserDefaults standardUserDefaults];
                NSString *paperIDWithName =[NSString stringWithFormat:@"%@_%@",[_urlDict objectForKey:@"paperID"],@"userName"];
                [standard setObject:@"0" forKey:paperIDWithName];
                NSString *paperID =[NSString stringWithFormat:@"%@",[_urlDict objectForKey:@"paperID"]];
                if ([Sqlite updateUserAnswer:@"" paperId:paperID]) {
                    FMSCHBLog(@"取消做题记录!");
                }else{
                    FMSCHBLog(@"取消保存做题记录失败！");
                }
                BOOL success = [Sqlite updateCurrentPageFlag:0 paperId:paperID];
                if (success) {
                    FMSCHBLog(@"保存进度成功");
                }else{
                    FMSCHBLog(@"保存进度失败");
                }
                if (IS_STUDY) {
                    BOOL success = [Sqlite updateUserAnswerImage:@"" paperId:paperID];
                    if (success) {
                        FMSCHBLog(@"userAnswerImage状态重置保存成功!");
                    }else{
                        FMSCHBLog(@"userAnswerImage状态保存失败!");
                    }
                    NSString *imagePath = [NSString stringWithFormat:@"%@/%@/image",FMPAPERSAVE_PATH,paperID];
                    [ApplicationUtils deleteExitsFile:imagePath];
                    isReset = @"3";
                    BOOL isReachable = [[FMReachability FMReachabilityWithHostname:@"www.baidu.com"] isReachable];
                    if (isReachable) {
                        [self submitHomeWork:@"1"];
                    }else{
                        [self showTestPaper];
                    }
                }else{
                    [self showTestPaper];
                }
            }
            if (alertView.tag == 3){
                //更新做题ueser_answer =@""; 取消做题记录
//                NSString *paperID =[NSString stringWithFormat:@"%@",[_urlDict objectForKey:@"paperID"]];
//                if ([Sqlite updateUserAnswer:@"" paperId:paperID]) {
//                    NSUserDefaults *standard = [NSUserDefaults standardUserDefaults];
//                    NSString *paperIDWithName =[NSString stringWithFormat:@"%@_%@",[_urlDict objectForKey:@"paperID"],@"userName"];
//                    [standard setObject:@"0" forKey:paperIDWithName];
//                    [self dismissViewControllerAnimated:YES completion:^{
//                        
//                    }];
//                    BOOL success = [Sqlite updateUserAnswerImage:@"" paperId:paperID];
//                    if (success) {
//                        FMSCHBLog(@"userAnswerImage状态重置保存成功!");
//                    }else{
//                        FMSCHBLog(@"userAnswerImage状态保存失败!");
//                    }
//                }else{
//                    FMSCHBLog(@"取消保存做题记录失败！");
//                }
                [self dismissViewControllerAnimated:YES completion:^{
                    
                }];
            }
            if (alertView.tag == 4){//试卷加载失败1
//                [self dismissViewControllerAnimated:YES completion:^{
//                    
//                }];
            }
            if (alertView.tag == 5) {
                if (self.rootTimer) {
                    [self.rootTimer setFireDate:[NSDate date]];
                }
            }
        }
            break;
        case 1:
        {
            if (alertView.tag == 1) {//交卷
                if (IS_STUDY) {
                    isReset = nil;
                    [self submitHomeWork:@"2"];
                    
//                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"作业已提交请耐心等待成绩" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//                    [alertView show];
//                    [self.navigationController dismissViewControllerAnimated:YES completion:^{
//                        //后台提交作业
//                        
//                    }];
                    return;
                }
//                NSUserDefaults *standard = [NSUserDefaults standardUserDefaults];
//                NSString *paperIDWithName =[NSString stringWithFormat:@"%@_%@",[_urlDict objectForKey:@"paperID"],@"userName"];
//                [standard setObject:@"0" forKey:paperIDWithName];//判断是否做过试题
                NSString *paperId = [NSString stringWithFormat:@"%@",[_urlDict objectForKey:@"paperID"]];
//                if ([Sqlite deleteTestQuestionIdAt:paperId]) {//清除试题成功
//                    FMSCHBLog(@"试题清除成功");
//                }else{
//                    FMSCHBLog(@"试题清除失败!");
//                }
                
                BOOL success = [Sqlite updateCurrentPageFlag:0 paperId:paperId];
                if (success) {
                    FMSCHBLog(@"保存进度成功");
                }else{
                    FMSCHBLog(@"保存进度失败");
                }
                //计算准备数据
                NSMutableDictionary *dataDict = [NSMutableDictionary dictionaryWithCapacity:1];
                [dataDict setObject:paperId forKey:@"paper_id"];
                [dataDict setObject:paper_title forKey:@"paper_title"];
                //实例化一个NSDateFormatter对象
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                //设定时间格式,这里可以设置成自己需要的格式
                [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                //用[NSDate date]可以获取系统当前时间
                NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
                //输出格式为：2010-10-27 10:22:13
                [dataDict setObject:currentDateStr forKey:@"exam_time"];
                
                [dataDict setObject:paper_time forKey:@"paper_time"];
                [dataDict setObject:paper_score forKey:@"paper_score"];
//                NSString *second_ =[NSString stringWithFormat:@"%d",180];//
                
                [dataDict setObject:_user_time forKey:@"exam_use_time"];//
                
                NSInteger count = [self.paperArray count];
                NSString *scroeStr = [NSString stringWithFormat:@"%ld",(long)Sum];
                [dataDict setObject:scroeStr forKey:@"exam_score"];

                NSString *qst_count = [NSString stringWithFormat:@"%ld",(long)count];
                [dataDict setObject:qst_count forKey:@"qst_count"];
                [dataDict setObject:@"0" forKey:@"order_rule"];
                NSString *exit_qst_id = [NSString stringWithFormat:@"%ld",(long)_currentPage];
                [dataDict setObject:exit_qst_id forKey:@"exit_qst_id"];
                [dataDict setObject:@"试题来源" forKey:@"soure"];
                [dataDict setObject:@"真题" forKey:@"type"];
                [dataDict setObject:[NSString stringWithFormat:@"%ld",(long)Sum] forKey:@"sum"];
                
                [dataDict setObject:@"1" forKey:@"finish_flag"];//我的成绩
                BOOL sucess = [Sqlite addPaper:dataDict];
                if (!sucess) {
                    FMSCHBLog(@"success:----存储失败！---");
                    return;
                }
                if (IS_STUDY) {
                    NSString *paperID =[NSString stringWithFormat:@"%@",[_urlDict objectForKey:@"paperID"]];
                    if ([Sqlite updateUserAnswer:@"" paperId:paperID]) {
                        FMSCHBLog(@"取消做题记录!");
                    }else{
                        FMSCHBLog(@"取消保存做题记录失败！");
                    }
                    for (NSMutableDictionary *dataDict in self.paperArray) {
                        [dataDict setObject:currentDateStr forKey:@"exam_time"];
                        BOOL success = [Sqlite insertQuestion:dataDict];
                        if (success) {
                            FMSCHBLog(@"success:----存储成功！---");
                        }
                    }
                }
                //新建一个数据库，保存做完的试题，已被查看成绩使用
                __weak TestRootViewController *weakSelf = self;
                ResultViewController *resultVC = [[ResultViewController alloc] initWithNibName:@"ResultViewController" bundle:nil];
                resultVC.resultBackBlock = ^(){
                    if (weakSelf.testVCBackBlock) {
                        weakSelf.testVCBackBlock(weakSelf);
                    }
                };
                resultVC.dataDict = dataDict;
                [self.navigationController pushViewController:resultVC animated:YES];
            }else if (alertView.tag == 2){
                [self showTestPaper];
            }else if (alertView.tag == 3){//保存做题记录
                if (IS_STUDY) {
                    isReset = nil;
                    [self submitHomeWork:@"1"];
                    return;
                }else{
                    NSString *paperID =[NSString stringWithFormat:@"%@",[_urlDict objectForKey:@"paperID"]];
                   BOOL success = [Sqlite updateCurrentPageFlag:_currentPage paperId:paperID];
                    if (success) {
                        FMSCHBLog(@"保存进度成功");
                    }else{
                        FMSCHBLog(@"保存进度失败");
                    }
                    [self dismissViewControllerAnimated:YES completion:^{
                        
                    }];
                }
            }
        }
            break;
        default:
            break;
    }
}
- (void)HBTableViewFooterView:(HBTableViewFooterView *)footerView webViewDidFinishLoad:(UIWebView *)webView{
    HBListTableView *tableView = (HBListTableView *)[_swipeView itemViewAtIndex:_currentPage];
    tableView.tableFooterView = footerView;
}
#pragma mark UIAlertViewDelegate
#pragma --
-(void)submitBtnClicked:(UIButton *)sender{
    if (isExercise) {//练习,点击显示答案
        NSDictionary *dataDict = [self.paperArray objectAtIndex:_currentPage];
        HBListTableView *tableView = (HBListTableView *)[_swipeView itemViewAtIndex:_currentPage];
        HBTableViewFooterView *footerView = [[HBTableViewFooterView alloc] initWithFrame:CGRectMake(0, 0, 320, 70)];
        [footerView setDelegate:self];
        [footerView setDataReload:dataDict];
        tableView.tableFooterView = footerView;
    }else{
        NSString *msg = nil;
        if (IS_STUDY) {
            msg =@"确定交作业吗?";
        }else{
            msg =@"确定交卷吗?";
        }
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alertView.tag = 1;
        [alertView show];
    }
}
#pragma mark 底部按钮点击事件
#pragma --
//上一页
-(void)upBtnClicked:(UIButton *)sender{
    if (_currentPage==0) {
        [ApplicationUtils makeToast:@"已第一页" withImageName:@"no" withView:self.view];
        return;
    }
    [_swipeView scrollToPage:_currentPage-1 duration:0.5];
}
//收藏
-(void)favBtnClicked:(UIButton *)sender{
    NSMutableDictionary *dataDict = (NSMutableDictionary *)[self.paperArray objectAtIndex:_currentPage];
    if (!dataDict) {
        return;
    }
    NSString *qstId =[dataDict objectForKey:@"qstId"];
    NSString *paperId = [NSString stringWithFormat:@"%@",[dataDict objectForKey:@"paper_id"]];
    NSString *favourite_flag = [NSString stringWithFormat:@"%@",[dataDict objectForKey:@"favourite_flag"]];
    BOOL isCollection = NO;
    if ([favourite_flag isEqualToString:@"1"]) {
        isCollection = YES;
    }
    if (!isCollection) {
        if ([Sqlite updateCollection:@"1" orderId:qstId paperId:paperId]) {
            [ApplicationUtils makeToast:@"收藏成功" withImageName:@"Star" withView:self.view];
            FMSCHBLog(@"收藏成功");
            [dataDict setObject:@"1" forKey:@"favourite_flag"];
        }else{
            [ApplicationUtils makeToast:@"收藏失败!" withImageName:@"Star" withView:self.view];
            FMSCHBLog(@"收藏失败");
        }
    }else{
        if ([Sqlite updateCollection:@"0" orderId:qstId paperId:paperId]) {
            FMSCHBLog(@"取消收藏");
            [ApplicationUtils makeToast:@"取消收藏!" withImageName:@"Star" withView:self.view];
            [dataDict setObject:@"0" forKey:@"favourite_flag"];
        }else{
            [ApplicationUtils makeToast:@"取消收藏失败!" withImageName:@"Star" withView:self.view];
            FMSCHBLog(@"取消收藏失败!");
        }
    }
    [sender setSelected:!isCollection];
}
//下一页
-(void)downBtnClicked:(UIButton *)sender{
    if ([self.paperArray count]-1 == _currentPage) {
        [ApplicationUtils makeToast:@"已最后一页" withImageName:@"no" withView:self.view];
        return;
    }
    [_swipeView scrollToPage:_currentPage+1 duration:0.5];
}
-(void)draftBtnClicked:(id)sender{
    UIWindow *keyWindow =  [UIApplication sharedApplication].keyWindow;
    DraftViewController *draft = [[DraftViewController alloc] initWithFrame:[UIScreen mainScreen].bounds WithView:keyWindow];
    [draft pushToView];
}
-(void)answerBtnClicked:(id)sender{
//    FMTxtPhotoViewController  *txt = [[FMTxtPhotoViewController alloc] init];
//    [self presentViewController:txt animated:YES completion:^{
//        
//    }];
}
-(void)initCamerView{
    CGRect rect = [UIScreen mainScreen].bounds;
//    if(!_imgv){
//        _imgv = [[SimpleFooterView alloc] initWithFrame:CGRectMake(0, rect.size.height-50-90-20, rect.size.width, 50)];
//    }
//    [_imgv setDelegate:self];
//    [self.view addSubview:_imgv];
    if (!_answerBtn) {
        _answerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_answerBtn setFrame:CGRectMake(rect.size.width-50, rect.size.height-50-90-20, 21, 20)];
        [_answerBtn setBackgroundImage:[ApplicationUtils getLocalImage:@"HomeKeyPointCellExerciseButtonPressed"] forState:UIControlStateNormal];
        [_answerBtn setBackgroundImage:[ApplicationUtils getLocalImage:@"HomeKeyPointCellExerciseButtonPressed@2x"] forState:UIControlStateHighlighted];
        [_answerBtn addTarget:self action:@selector(answerBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    [self.view addSubview:_answerBtn];
}
-(void)initSelfView{
    FMSCHBLog(@"FMSCREENWIDTH:%f",FMSCREENWIDTH);
    headerBg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, FMSCREENWIDTH, 25)];
    [headerBg setBackgroundColor:[ApplicationUtils stringTOColor:@"#2d2827"]];
    //    [headerBg setAlpha:0.5];
    [self.view sendSubviewToBack:headerBg];
    [self.view addSubview:headerBg];
    
    //header
    titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, FMSCREENWIDTH, 25)];
    [titleLabel setText:@""];
    [titleLabel setBackgroundColor:[UIColor clearColor]];
    [titleLabel setTextColor:[UIColor whiteColor]];
    [self.view addSubview:titleLabel];

    //footer
    UIImage *footerBg = [[ApplicationUtils getLocalImage:@"app_footer_bg"] resizableImageWithCapInsets:UIEdgeInsetsMake(5.0, 5.0, 5.0, 5.0)];
    UIImageView *footer = [[UIImageView alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height-20-44-50, FMSCREENWIDTH, 90)];
    [footer setImage:footerBg];
    //上一页
//    UIButton *upButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    [upButton setImage:[UIImage getLocalImage:@"exam_icon_previous"] forState:UIControlStateNormal];
//    [upButton setImage:[UIImage getLocalImage:@"exam_icon_previous_pressed"] forState:UIControlStateHighlighted];
//    [upButton setTitle:@"上一页" forState:UIControlStateNormal];
//    [upButton setTitle:@"上一页" forState:UIControlStateHighlighted];
//    [[upButton titleLabel] setFont:[UIFont systemFontOfSize:8.0]];
//    [upButton setTitleEdgeInsets:UIEdgeInsetsMake(20, -50, 0, 0)];
//    [upButton setImageEdgeInsets:UIEdgeInsetsMake(0, 5, 15, 5)];
//    [upButton setFrame:CGRectMake(20, (50-30)/2, 45, 45)];
//    [upButton addTarget:self action:@selector(upBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
//    [footer addSubview:upButton];
    
    //答案
    UIButton *answerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [answerButton setImage:[ApplicationUtils getLocalImage:@"st_Options_submit1@2x"] forState:UIControlStateNormal];
    [answerButton setImage:[ApplicationUtils getLocalImage:@"st_Options_submit@2x"] forState:UIControlStateHighlighted];
    if (isExercise) {
        [answerButton setTitle:@"答案" forState:UIControlStateNormal];
        [answerButton setTitle:@"答案" forState:UIControlStateHighlighted];
    }else {
        if (IS_STUDY) {
            [answerButton setTitle:@"交作业" forState:UIControlStateNormal];
            [answerButton setTitle:@"交作业" forState:UIControlStateHighlighted];
        }else{
            [answerButton setTitle:@"交卷" forState:UIControlStateNormal];
            [answerButton setTitle:@"交卷" forState:UIControlStateHighlighted];
        }
    }
    [answerButton setTitleColor:[ApplicationUtils stringTOColor:@"#1cb6a7"] forState:UIControlStateHighlighted];
    [answerButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    [answerButton setImageEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 25)];
    [[answerButton titleLabel] setFont:[UIFont systemFontOfSize:14.0]];
    [answerButton setFrame:CGRectMake(FMSCREENWIDTH/2-100, (50-30)/2, 100, 30)];
    [answerButton addTarget:self action:@selector(submitBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [footer addSubview:answerButton];
    if (EDUCATION) {
        //收藏
        UIButton *favButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [favButton setImage:[ApplicationUtils getLocalImage:@"st_Options_Collection1@2x"] forState:UIControlStateNormal];
        [favButton setImage:[ApplicationUtils getLocalImage:@"st_Options_Collection@2x"] forState:UIControlStateHighlighted];
        [favButton setImage:[ApplicationUtils getLocalImage:@"st_Options_Collection@2x"] forState:UIControlStateSelected];
        [favButton setTitle:@"收藏" forState:UIControlStateNormal];
        [favButton setTitle:@"收藏" forState:UIControlStateHighlighted];
        [favButton setTitle:@"取消收藏" forState:UIControlStateSelected];
        [favButton setTitleColor:[ApplicationUtils stringTOColor:@"#1cb6a7"] forState:UIControlStateHighlighted];
        [favButton setTitleColor:[ApplicationUtils stringTOColor:@"#1cb6a7"] forState:UIControlStateSelected];
        [[favButton titleLabel] setFont:[UIFont systemFontOfSize:14.0]];
        collectionBtn= favButton;
        [favButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
        [favButton setImageEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 30)];
        [favButton setFrame:CGRectMake(FMSCREENWIDTH/2+30, (50-30)/2, 100, 30)];
        [favButton addTarget:self action:@selector(favBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [footer addSubview:favButton];
    }else{
        [answerButton setFrame:CGRectMake((FMSCREENWIDTH-100)/2, (50-30)/2, 100, 30)];
        //上一页
        UIButton *upBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [upBtn setBackgroundImage:[UIImage imageNamed:@"exam_icon_previous_pressed.png"] forState:UIControlStateNormal];
        [upBtn setBackgroundImage:[UIImage imageNamed:@"exam_icon_previous.png"] forState:UIControlStateHighlighted];
        [upBtn setFrame:CGRectMake(50, 10, 28, 27)];
        [upBtn addTarget:self action:@selector(upBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [footer addSubview:upBtn];
        
        //下一页
        UIButton *downBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [downBtn setBackgroundImage:[UIImage imageNamed:@"exam_icon_next_pressed.png"] forState:UIControlStateNormal];
        [downBtn setBackgroundImage:[UIImage imageNamed:@"exam_icon_next.png"] forState:UIControlStateHighlighted];
        [downBtn setFrame:CGRectMake(FMSCREENWIDTH-50-28, 10, 28, 27)];
        [downBtn addTarget:self action:@selector(downBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [footer addSubview:downBtn];
    }
    //下一页
    if (IS_STUDY) {
        //暂时注销
//        UIButton *downButton = [UIButton buttonWithType:UIButtonTypeCustom];
//        [downButton setImage:[ApplicationUtils getLocalImage:@"NavigationScratchPaperButton@2x"] forState:UIControlStateNormal];
//        [downButton setImage:[ApplicationUtils getLocalImage:@"NavigationScratchPaperButtonPressed@2x"] forState:UIControlStateHighlighted];
//        [downButton setFrame:CGRectMake(FMSCREENWIDTH-60, 0, 40, 40)];
//        [downButton addTarget:self action:@selector(draftBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
//        [footer addSubview:downButton];
    }
//    footer.translatesAutoresizingMaskIntoConstraints = NO;
//    NSLayoutConstraint *layOut1 = [NSLayoutConstraint constraintWithItem:answerButton attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:footer attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:-100.0];
//    [footer addConstraint:layOut1];
//    
//    NSLayoutConstraint *layOut2 = [NSLayoutConstraint constraintWithItem:favButton attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:footer attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:+100.0];
//    [footer addConstraint:layOut2];
    if([self respondsToSelector:@selector(setAutomaticallyAdjustsScrollViewInsets:)]){
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [footer setUserInteractionEnabled:YES];
    [self.view addSubview:footer];
    
}
-(void)showMainAnswerView{
//    [ApplicationUtils promptRotateWithViewTitle:@"加载中..." showView:self.view];
//    NSString *paperId = [NSString stringWithFormat:@"%@",[_urlDict objectForKey:@"paperID"]];
    //    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    //    NSString *pathStr = [NSString stringWithFormat:@"%@/paper.XML",path];
    //    NSString *paperXmlString = [NSString stringWithContentsOfFile:pathStr encoding:NSUTF8StringEncoding error:nil];
    //    SynExericisesPaperData *paperData = [[SynExericisesPaperData alloc] init];
    //    NSMutableDictionary *paperDict = [paperData PaperData:paperXmlString];
    //    FMSCHBLog(@"paperDict:%@",paperDict);
    //    if (!self.dataQuestionDict) {
    //        self.dataQuestionDict = [NSMutableDictionary dictionaryWithDictionary:paperDict];
    //    }
//    NSMutableArray *array_afterSave = [Sqlite selectTestQuestion:paperId];
//    if (!self.paperArray) {
//        self.paperArray = [NSMutableArray arrayWithCapacity:1];
//    }
//    [self.paperArray addObjectsFromArray:array_afterSave];//存为全局，以后使用
//    paper_title = nil;
//    paper_score = nil;
//    paper_time = nil;
//    if ([self.paperArray count]>0) {
//        paper_title = [[self.paperArray objectAtIndex:0] objectForKey:@"paper_title"];
//        paper_score = [[self.paperArray objectAtIndex:0] objectForKey:@"paper_score"];
//        paper_time = [[self.paperArray objectAtIndex:0] objectForKey:@"paper_time"];
//    }else{
//        FMSCHBLog(@"----cuihongbao-----加载数据失败!");
//        [ApplicationUtils promptRemove];
//        return;
//    }
//    [self initTestView:paper_title];
}
-(void)initAnswerData{
    NSString *paperId = [NSString stringWithFormat:@"%@",[self.urlDict objectForKey:@"paperID"]];
    NSString *authToken = [NSString stringWithFormat:@"%@",[self.urlDict objectForKey:@"authToken"]];
    NSString  *plistPath = [[NSBundle mainBundle] pathForResource:@"Config" ofType:@"plist"];
    NSMutableDictionary *dataDict = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
    NSString *ip_host = [dataDict objectForKey:@"ip_host"];
    NSString *ip_root = [dataDict objectForKey:@"ip_root"];
    NSString *urlString = [NSString stringWithFormat:@"http://%@%@getUserExamResult.do?homeworkid=%@&authToken=%@",ip_host,ip_root,paperId,authToken];
    //初始化Documents路径
    NSString *path = [NSString stringWithFormat:@"%@/%@",FMPAPERSAVE_PATH,paperId];//[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Paper"];
    FMSCHBLog(@"FMPAPERSAVE_PATH:%@",FMPAPERSAVE_PATH);
    if ([ApplicationUtils isFileExitsAtPath:path]) {
        FMSCHBLog(@"创建目录成功");
    }
    //初始化保存ZIP文件路径
    if ([Sqlite deleteTestQuestionIdAt:paperId]) {//清除试题成功，之后再保存
        FMSCHBLog(@"试题清除成功");
    }else{
        FMSCHBLog(@"试题清除失败!");
    }
    NSString *filePath = [path stringByAppendingPathComponent:@"answer.zip"];
//    [ApplicationUtils promptRotateWithViewTitle:@"加载中..." showView:self.view];
    [[FMSNetWorkModule sharedInstance] downloadFatAssFileFrom:urlString toFile:filePath completionCB:^(id result) {
        if (result == nil) {
            //初始化ZipArchive
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
                                                     0), ^{
//ios 不用删除自动适配
//                //删除本地的json文件和image下的图片
//                NSString *pathStrJ = [NSString stringWithFormat:@"%@/%@",FMPAPERSAVE_PATH,paperId];
////                NSString *pathStrJ = [NSString stringWithFormat:@"%@/answer.json",path];
//                [ApplicationUtils deleteExitsFile:pathStrJ];
//                pathStrJ =[NSString stringWithFormat:@"%@/image",pathStrJ];
//                [ApplicationUtils deleteExitsFile:pathStrJ];
                
                ZipArchive *zip = [[ZipArchive alloc] init];
                BOOL success = NO;
                if ([zip UnzipOpenFile:filePath]) {
                    success = [zip UnzipFileTo:path overWrite:YES];//解压文件
                    [zip UnzipCloseFile];//关闭
                    if (success) {
                        //解压成功
                        FMSCHBLog(@"unzip success.............");
//                        NSString *status = [self.urlDict objectForKey:@"status"];
//                        if ([status isEqualToString:@"1"]) {
                            @try {
                                //同步试卷数据中zip包的数据到数据库
                                NSString *pathStr = [NSString stringWithFormat:@"%@/answer.json",path];
                                NSString *jsonStr = [[NSString alloc]initWithContentsOfFile:pathStr encoding:NSUTF8StringEncoding error:nil];
                                NSArray *dataArray = [ApplicationUtils objectFromJson:jsonStr];
                                for (NSDictionary *answerDict in dataArray) {
                                    NSString *qstId = [answerDict objectForKey:@"qstId"];
                                    NSString *author_id = [[NSUserDefaults standardUserDefaults]objectForKey:@"userName"];
                                    //删除重复图片文件成功
//                                    NSString *selectSQL = [NSString stringWithFormat:@"select user_answer from testQuestionTable where author_id ='%@' and paper_id = '%@' and qstId = '%@';",author_id,paperId,qstId];
//                                   NSMutableArray *array = [Sqlite selectSimpleQuestion:selectSQL];
//                                    for (NSDictionary *dict in array) {
//                                        NSString *user_answer = [dict objectForKey:@"user_answer"];
//                                        if ([user_answer hasSuffix:@"png"]) {
//                                            NSString *filePath = [NSString stringWithFormat:@"%@/%@/image/%@",FMPAPERSAVE_PATH,paperId,user_answer];
//                                            BOOL success = [ApplicationUtils deleteExitsFile:filePath];
//                                            if (success) {
//                                                FMSCHBLog(@"-------删除重复图片文件成功文件-------");
//                                            }
//                                        }
//                                    }
                                    //同步答案
                                    NSString *user_answer = [answerDict objectForKey:@"userAnswer"];
                                    NSString *userAnswerImage = [answerDict objectForKey:@"userAnswerImage"];
                                    NSString *updateSQL = [NSString stringWithFormat:@"update testQuestionTable set user_answer = '%@',userAnswerImage='%@' where  paper_id='%@' and author_id ='%@' and qstId = '%@' ;", user_answer,userAnswerImage,paperId,author_id,qstId];
                                    BOOL success =[Sqlite updateUserAnswer:updateSQL];
                                    if (success) {
                                        FMSCHBLog(@"---更新答案成功---");
                                    }
                                }
                            }
                            @catch (NSException *exception) {
                                dispatch_async(dispatch_get_main_queue(), ^{
//                                    [ApplicationUtils showAlertMSG:[exception description]];
                                    FMSCHBLog(@"exception---------%@",[exception description]);
                                });
                            }
                            @finally {
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    [ApplicationUtils promptRemove];
                                    //下载完成回调方式通知TestViewController更新界面
                                    [[NSNotificationCenter defaultCenter] postNotificationName:@"FILE_DOWNDONE" object:nil userInfo:nil];
                                });
                                return;
                            }
//                        }
                        //删除answer.zip文件
                        BOOL success1 = [ApplicationUtils deleteExitsFile:filePath];
                        if (success1) {
                            FMSCHBLog(@"删除zip文件成功");
                        }
                    }else {
                        FMSCHBLog(@"zip UnzipFileTo fail................");
                    }
                }else{
                    FMSCHBLog(@"open fail................");
                }
            });
        }else{
            [ApplicationUtils promptRemove];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"试卷同步加载失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert setTag:4];
            [alert show];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"FILE_DOWNDONE" object:nil userInfo:nil];
        }
        //下载完成回调方式通知TestViewController更新界面
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"FILE_DOWNDONE" object:nil userInfo:nil];
    }];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initSelfView];
    CGRect rect = [[UIScreen mainScreen] bounds];
    int h = rect.size.height-44-35-50-20;
    if (!_swipeView) {
        _swipeView = [[SwipeView alloc] initWithFrame:CGRectMake(0, 35, FMSCREENWIDTH, h)];
        _swipeView.alignment = SwipeViewAlignmentCenter;
        _swipeView.delegate = self;
        _swipeView.dataSource = self;
        _swipeView.pagingEnabled = YES;
        _swipeView.wrapEnabled = NO;
        _swipeView.itemsPerPage = 1;
        _swipeView.truncateFinalPage = YES;
        [_swipeView setBackgroundColor:[UIColor clearColor]];
        [self.view addSubview:_swipeView];
    }
    if (IS_STUDY) {
        if (!self.homeworkArray) {
            self.homeworkArray = [NSMutableArray arrayWithCapacity:1.0];
        }
    }
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sysHomeWork) name:UIApplicationDidBecomeActiveNotification object:nil];
    if(IS_STUDY){
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sysHomeWork) name:UIApplicationDidEnterBackgroundNotification object:nil];
    }
}
-(void)sysHomeWork{
    UIApplication *application = [UIApplication sharedApplication];
    //通知系统, 我们需要后台继续执行一些逻辑
    backgroundTask = [application beginBackgroundTaskWithExpirationHandler:^{
        //超过系统规定的后台运行时间, 则暂停后台逻辑
        [application endBackgroundTask:backgroundTask];
        backgroundTask = UIBackgroundTaskInvalid;
    }];
    
    //判断如果申请失败了, 返回
    if (backgroundTask == UIBackgroundTaskInvalid) {
        FMSCHBLog(@"beginground error");
        return;
    }
    //已经成功向系统争取了一些后台运行时间, 实现一些逻辑, 如网络处理
    //some code
    isReset = nil;
    [self submitHomeWork:@"1"];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    if (IS_STUDY) {
//        
//    }else{
//        self.navigationController.navigationBarHidden = NO;
//    }
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
//    if (IS_STUDY) {
//        
//    }else{
//        self.navigationController.navigationBarHidden = YES;
//    }
//    [self releaseMyDealloc];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    FMSCHBLog(@"===***********TestRootViewController==didReceiveMemoryWarning=====");
//    [self releaseMyDealloc];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark  UIImagePickerController
#pragma -
-(void)photoBtnClicked:(UIButton *)sender{
    _photoBtn = sender;//点击拍照的按钮
    if (([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)){
        NSString *mediaType = AVMediaTypeVideo;// Or AVMediaTypeAudio
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
        // This status is normally not visible—the AVCaptureDevice class methods for discovering devices do not return devices the user is restricted from accessing.
        if(authStatus ==AVAuthorizationStatusRestricted){
            FMSCHBLog(@"Restricted");
        }else if(authStatus == AVAuthorizationStatusDenied){
            // The user has explicitly denied permission for media capture.
            FMSCHBLog(@"Denied");     //应该是这个，如果不允许的话
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"请在设备设置中允许访问相机。"
                                                           delegate:nil
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:nil];
            [alert show];
            return;
        }
        else if(authStatus == AVAuthorizationStatusAuthorized){//允许访问
            // The user has explicitly granted permission for media capture, or explicit user permission is not necessary for the media type in question.
            FMSCHBLog(@"Authorized");
            [self showCamera];
            
        }else if(authStatus == AVAuthorizationStatusNotDetermined){
            // Explicit user permission is required for media capture, but the user has not yet granted or denied such permission.
            [AVCaptureDevice requestAccessForMediaType:mediaType completionHandler:^(BOOL granted) {
                if(granted){//点击允许访问时调用
                    //用户明确许可与否，媒体需要捕获，但用户尚未授予或拒绝许可。
                    FMSCHBLog(@"Granted access to %@", mediaType);
                    [self showCamera];
                }
                else {
                    FMSCHBLog(@"Not granted access to %@", mediaType);
                }
                
            }];
        }else {
            FMSCHBLog(@"Unknown authorization status");
        }
    }else{
        [self showCamera];
    }
}
//对图片尺寸进行压缩--
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}
//成功获得相片还是视频后的回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    //通过UIImagePickerControllerMediaType判断返回的是照片还是视频
    NSString* type = [info objectForKey:UIImagePickerControllerMediaType];
    //如果返回的type等于kUTTypeImage，代表返回的是照片,并且需要判断当前相机使用的sourcetype是拍照还是相册
    if ([type isEqualToString:(NSString*)kUTTypeImage]&&picker.sourceType==UIImagePickerControllerSourceTypeCamera) {
        editeImage = [info objectForKey:UIImagePickerControllerEditedImage];
        //设置image的尺寸
        CGSize imagesize = editeImage.size;
        imagesize.height =600;
        imagesize.width =600;
        editeImage = [self imageWithImage:editeImage scaledToSize:imagesize];
       NSInteger   pageIndex =  _swipeView.currentPage;
        NSString *fileName = [NSString stringWithFormat:@"%@_%ld.png",[self.urlDict objectForKey:@"paperID"],(long)pageIndex];
        NSMutableDictionary *dataDict = [self.paperArray objectAtIndex:pageIndex];
        //照相重新拍摄删除之前的图片
//        NSString *pathOld = [NSString stringWithFormat:@"%@/%@/image/%@",FMPAPERSAVE_PATH,[self.urlDict objectForKey:@"paperID"],[dataDict objectForKey:@"user_answer"]];
//        BOOL oldImageFile = [ApplicationUtils deleteExitsFile:pathOld];
//        FMSCHBLog(@"oldImageFile---->:%d",oldImageFile);
        
        NSString *pngPath = [self pngFilePath];
        [UIImagePNGRepresentation(editeImage) writeToFile:pngPath atomically:YES];
        [dataDict setObject:@"2" forKey:@"userAnswerImage"];
        [dataDict setObject:fileName forKey:@"user_answer"];
        //答案保存在数据库
        NSString *qstId = [dataDict objectForKey:@"qstId"];
        NSString *paperId = [NSString stringWithFormat:@"%@",[_urlDict objectForKey:@"paperID"]];
        BOOL success;
        success = [Sqlite updateUserAnswer:fileName  user_right_count:@"1"title_id:qstId paperId:paperId];
        if (success) {
            FMSCHBLog(@"保存成功!");
        }else{
            FMSCHBLog(@"保存失败!");
        }
        success = [Sqlite updateUserAnswerImage:@"2" paperId:paperId title_id:qstId];
        if (success) {
            FMSCHBLog(@"userAnswerImage状态保存成功!");
        }else{
            FMSCHBLog(@"userAnswerImage状态保存失败!");
        }
        
        NSUserDefaults *standard = [NSUserDefaults standardUserDefaults];
        NSString *paperIDWithName =[NSString stringWithFormat:@"%@_%@",[_urlDict objectForKey:@"paperID"],@"userName"];
        [standard setObject:@"1" forKey:paperIDWithName];//判断是否做过试题
        
        // 更新界面
        float Version=[[[UIDevice currentDevice] systemVersion] floatValue];
        HBSimpleTableViewCell *simpleCell = nil;
        if(Version<8.0)
        {
            simpleCell  = (HBSimpleTableViewCell *)_photoBtn.superview.superview;
        }else{
            simpleCell  = (HBSimpleTableViewCell *)_photoBtn.superview;
        }
        UIImageView *mageView = (UIImageView *)[simpleCell.photoImageView viewWithTag:100];
        UIImage *image = [UIImage imageWithContentsOfFile:pngPath];
        [mageView setImage:image];
    }else{
        
    }
    //模态方式退出uiimagepickercontroller
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}
//取消照相机的回调
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    //模态方式退出uiimagepickercontroller
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}
//保存照片成功后的回调
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error
  contextInfo:(void *)contextInfo{
    
    FMSCHBLog(@"saved..");
}
-(void)showCamera{
    UIImagePickerController *imagepicker =  [[UIImagePickerController alloc] init];
    //指定使用照相机模式,可以指定使用相册／照片库
    imagepicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    //设置当拍照完或在相册选完照片后，是否跳到编辑模式进行图片剪裁。只有当showsCameraControls属性为true时才有效果
    imagepicker.allowsEditing = YES;
    //设置拍照时的下方的工具栏是否显示，如果需要自定义拍摄界面，则可把该工具栏隐藏
    imagepicker.showsCameraControls  = YES;
    //设置使用后置摄像头，可以使用前置摄像头
    imagepicker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
    //设置闪光灯模式
    /*
     typedef NS_ENUM(NSInteger, UIImagePickerControllerCameraFlashMode) {
     UIImagePickerControllerCameraFlashModeOff  = -1,
     UIImagePickerControllerCameraFlashModeAuto = 0,
     UIImagePickerControllerCameraFlashModeOn   = 1
     };
     */
    imagepicker.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
    //设置相机支持的类型，拍照和录像
    //    imagepicker.mediaTypes = @[(NSString*)kUTTypeImage,(NSString*)kUTTypeMovie];
    imagepicker.mediaTypes = @[(NSString*)kUTTypeImage];
    //设置拍摄时屏幕的view的transform属性，可以实现旋转，缩放功能
    // imagepicker.cameraViewTransform = CGAffineTransformMakeRotation(M_PI*45/180);
    // imagepicker.cameraViewTransform = CGAffineTransformMakeScale(1.5, 1.5);
    //所有含有cameraXXX的属性都必须要sourceType是UIImagePickerControllerSourceTypeCamera时设置才有效果，否则会有异常
    //设置UIImagePickerController的代理
    imagepicker.delegate = self;
    [self presentViewController:imagepicker animated:YES completion:^{
        
    }];
}

#pragma mark  SwipeViewDelegate
#pragma -
- (NSInteger)numberOfItemsInSwipeView:(SwipeView *)swipeView
{
    return [self.paperArray count];
}
- (UIView *)swipeView:(SwipeView *)swipeView viewForItemAtIndex:(NSInteger)index reusingView:(HBListTableView *)view
{
    if (view) {
        [view.loadedHeaders removeAllObjects];
        NSMutableDictionary *dataDict1 = [self.paperArray objectAtIndex:index];
        NSString *myqtype = [dataDict1 objectForKey:@"myqtype"];
       NSInteger  count =[Sqlite selectQuestionTypeCount:[self.urlDict objectForKey:@"paperID"] myqtype:myqtype];
        [dataDict1 setObject:[NSString stringWithFormat:@"%ld",(long)index] forKey:@"index"];
        [view setModelViewData:dataDict1 WithQuestionCount:count];
        view.tag = index;
        [view setHbdelegate:self];
       view.listViewBlock = ^(HBListTableView *listView,HBTableViewHeaderView *headerView){
        };
        
        view.listInputBlock = ^(HBListTableView *listView,NSString *text){
           NSInteger   pageIndex =  swipeView.currentPage;
            NSMutableDictionary *dataDict = [self.paperArray objectAtIndex:pageIndex];
            FMSCHBLog(@"-------index-------%ld",(long)index);
            NSString *user_answer = [dataDict objectForKey:@"user_answer"];
            if (![user_answer isEqualToString:@""]||!user_answer) {
                //删除草稿和相机图片文件
                NSString *strPath = [NSString stringWithFormat:@"%@/image/%@",[self.urlDict objectForKey:@"paperID"],user_answer];//图片路径
                NSString *path0 = [FMPAPERSAVE_PATH stringByAppendingPathComponent:strPath];
                BOOL sucess = [ApplicationUtils deleteExitsFile:path0];
                if (sucess) {
                    FMSCHBLog(@"-------删除图片成功--------");
                }else{
                    FMSCHBLog(@"-------删除图片失败--------");
                }
            }
            [dataDict setObject:text forKey:@"user_answer"];
            [dataDict setObject:@"0" forKey:@"userAnswerImage"];
            //答案保存在数据库
            NSString *qstId = [dataDict objectForKey:@"tq_id"];
            NSString *paperId = [NSString stringWithFormat:@"%@",[_urlDict objectForKey:@"paperID"]];
            BOOL success;
            success = [Sqlite updateUserAnswer:text  user_right_count:@"1"title_id:qstId paperId:paperId];
            if (success) {
                FMSCHBLog(@"保存成功!");
            }else{
                FMSCHBLog(@"保存失败!");
            }
            success = [Sqlite updateUserAnswerImage:@"0" paperId:paperId title_id:qstId];
            if (success) {
                FMSCHBLog(@"userAnswerImage状态保存成功!");
            }else{
                FMSCHBLog(@"userAnswerImage状态保存失败!");
            }
            
            NSUserDefaults *standard = [NSUserDefaults standardUserDefaults];
            NSString *paperIDWithName =[NSString stringWithFormat:@"%@_%@",[_urlDict objectForKey:@"paperID"],@"userName"];
            [standard setObject:@"1" forKey:paperIDWithName];//判断是否做过试题
        };
        
        /*
        view.listDraftBlock = ^(HBListTableView *listView,UIButton *btn){
            UIWindow *keyWindow =  [UIApplication sharedApplication].keyWindow;
            DraftViewController *draft = [[DraftViewController alloc] initWithFrame:[UIScreen mainScreen].bounds WithView:keyWindow];
            draft.draftBlock = ^(DraftViewController *draftView,UIImage *image){
                NSInteger   pageIndex =  swipeView.currentPage;
                NSMutableDictionary *dataDict = [self.paperArray objectAtIndex:pageIndex];
                NSString *user_answer = [dataDict objectForKey:@"user_answer"];
                if (![user_answer isEqualToString:@""]||!user_answer) {
                    //删除相机图片文件
                    NSString *strPath = [NSString stringWithFormat:@"%@/image/%@",[self.urlDict objectForKey:@"paperID"],user_answer];//图片路径
                    NSString *path0 = [FMPAPERSAVE_PATH stringByAppendingPathComponent:strPath];
                    BOOL sucess = [ApplicationUtils deleteExitsFile:path0];
                    if (sucess) {
                        FMSCHBLog(@"-------删除图片成功--------");
                    }else{
                        FMSCHBLog(@"-------删除图片失败--------");
                    }
                }
                NSString *fileName = [NSString stringWithFormat:@"%@_%ld.png",[self.urlDict objectForKey:@"paperID"],(long)listView.tag];
                NSString *pngPath = [self pngFilePath];
                [UIImagePNGRepresentation(image) writeToFile:pngPath atomically:YES];
                [dataDict setObject:@"1" forKey:@"userAnswerImage"];
                [dataDict setObject:fileName forKey:@"user_answer"];
                
                //答案保存在数据库
                NSString *qstId = [dataDict objectForKey:@"qstId"];
                NSString *paperId = [NSString stringWithFormat:@"%@",[_urlDict objectForKey:@"paperID"]];
                BOOL success;
                success = [Sqlite updateUserAnswer:fileName  user_right_count:@"1"title_id:qstId paperId:paperId];
                if (success) {
                    FMSCHBLog(@"保存成功!");
                }else{
                    FMSCHBLog(@"保存失败!");
                }
                success = [Sqlite updateUserAnswerImage:@"1" paperId:paperId title_id:qstId];
                if (success) {
                    FMSCHBLog(@"userAnswerImage状态保存成功!");
                }else{
                    FMSCHBLog(@"userAnswerImage状态保存失败!");
                }
                
                NSUserDefaults *standard = [NSUserDefaults standardUserDefaults];
                NSString *paperIDWithName =[NSString stringWithFormat:@"%@_%@",[_urlDict objectForKey:@"paperID"],@"userName"];
                [standard setObject:@"1" forKey:paperIDWithName];//判断是否做过试题
                // 更新界面
                float Version=[[[UIDevice currentDevice] systemVersion] floatValue];
                HBSimpleTableViewCell *simpleCell = nil;
                if(Version<8.0)
                {
                    simpleCell  = (HBSimpleTableViewCell *)btn.superview.superview;
                }else{
                    simpleCell  = (HBSimpleTableViewCell *)btn.superview;
                }
                UIImageView *mageView = (UIImageView *)[simpleCell.draftImageView viewWithTag:100];
                UIImage *image1 = [UIImage imageWithContentsOfFile:pngPath];
                [mageView setImage:image1];
            };
            [draft pushToView];
        };
        view.listPhotoBlock = ^(HBListTableView *listView,UIButton *btn){
            NSInteger   pageIndex =  swipeView.currentPage;
            NSMutableDictionary *dataDict = [self.paperArray objectAtIndex:pageIndex];
            NSString *user_answer = [dataDict objectForKey:@"user_answer"];
            if (![user_answer isEqualToString:@""]||!user_answer) {
                //删除草稿图片文件
                NSString *strPath = [NSString stringWithFormat:@"%@/image/%@",[self.urlDict objectForKey:@"paperID"],user_answer];//图片路径
                NSString *path0 = [FMPAPERSAVE_PATH stringByAppendingPathComponent:strPath];
                BOOL sucess = [ApplicationUtils deleteExitsFile:path0];
                if (sucess) {
                    FMSCHBLog(@"-------删除图片成功--------");
                }else{
                    FMSCHBLog(@"-------删除图片失败--------");
                }
            }
            [self photoBtnClicked:btn];
        };*/
        view.tableType = HBListTableViewTypeTest;
        return view;
    }
    NSMutableDictionary *dataDict1 = [self.paperArray objectAtIndex:index];
    HBListTableView *tableView = [[HBListTableView alloc] initWithFrame:CGRectMake(0, 0, FMSCREENWIDTH, swipeView.frame.size.height) style:UITableViewStyleGrouped];
    [dataDict1 setObject:[NSString stringWithFormat:@"%ld",(long)index] forKey:@"index"];
    NSString *myqtype = [dataDict1 objectForKey:@"myqtype"];
    NSInteger  count =[Sqlite selectQuestionTypeCount:[self.urlDict objectForKey:@"paperID"] myqtype:myqtype];
    [tableView setModelViewData:dataDict1 WithQuestionCount:count];
    tableView.tag = index;
    [tableView setHbdelegate:self];
    tableView.listViewBlock = ^(HBListTableView *listView,HBTableViewHeaderView *headerView){
    };
    /*tableView.listInputBlock = ^(HBListTableView *listView,NSString *text){
        
        NSInteger   pageIndex =  swipeView.currentPage;
        NSMutableDictionary *dataDict = [self.paperArray objectAtIndex:pageIndex];        FMSCHBLog(@"-------index-------%ld",(long)index);
        NSString *user_answer = [dataDict objectForKey:@"user_answer"];
        if (![user_answer isEqualToString:@""]||!user_answer) {
            //删除草稿和相机图片文件
            NSString *strPath = [NSString stringWithFormat:@"%@/image/%@",[self.urlDict objectForKey:@"paperID"],[dataDict objectForKey:@"user_answer"]];//图片路径
            NSString *path0 = [FMPAPERSAVE_PATH stringByAppendingPathComponent:strPath];
            BOOL sucess = [ApplicationUtils deleteExitsFile:path0];
            if (sucess) {
                FMSCHBLog(@"-------删除图片成功--------");
            }else{
                FMSCHBLog(@"-------删除图片失败--------");
            }
        }
        [dataDict setObject:text forKey:@"user_answer"];
        [dataDict setObject:@"0" forKey:@"userAnswerImage"];
        //答案保存在数据库
        NSString *qstId = [dataDict objectForKey:@"qstId"];
        NSString *paperId = [NSString stringWithFormat:@"%@",[_urlDict objectForKey:@"paperID"]];
        BOOL success;
        success = [Sqlite updateUserAnswer:text  user_right_count:@"1"title_id:qstId paperId:paperId];
        if (success) {
            FMSCHBLog(@"保存成功!");
        }else{
            FMSCHBLog(@"保存失败!");
        }
        success = [Sqlite updateUserAnswerImage:@"0" paperId:paperId title_id:qstId];
        if (success) {
            FMSCHBLog(@"userAnswerImage状态保存成功!");
        }else{
            FMSCHBLog(@"userAnswerImage状态保存失败!");
        }
        
        NSUserDefaults *standard = [NSUserDefaults standardUserDefaults];
        NSString *paperIDWithName =[NSString stringWithFormat:@"%@_%@",[_urlDict objectForKey:@"paperID"],@"userName"];
        [standard setObject:@"1" forKey:paperIDWithName];//判断是否做过试题
    };
    tableView.listDraftBlock = ^(HBListTableView *listView,UIButton *btn){
        UIWindow *keyWindow =  [UIApplication sharedApplication].keyWindow;
        DraftViewController *draft = [[DraftViewController alloc] initWithFrame:[UIScreen mainScreen].bounds WithView:keyWindow];
        draft.draftBlock = ^(DraftViewController *draftView,UIImage *image){
            NSInteger   pageIndex =  swipeView.currentPage;
            NSMutableDictionary *dataDict = [self.paperArray objectAtIndex:pageIndex];
            NSString *user_answer = [dataDict objectForKey:@"user_answer"];
                if (![user_answer isEqualToString:@""]||!user_answer) {
                    //删除相机图片文件
                    NSString *strPath = [NSString stringWithFormat:@"%@/image/%@",[self.urlDict objectForKey:@"paperID"],[dataDict objectForKey:@"user_answer"]];//图片路径
                    NSString *path0 = [FMPAPERSAVE_PATH stringByAppendingPathComponent:strPath];
                    BOOL sucess = [ApplicationUtils deleteExitsFile:path0];
                    if (sucess) {
                        FMSCHBLog(@"-------删除图片成功--------");
                    }else{
                        FMSCHBLog(@"-------删除图片失败--------");
                    }
                }
                NSString *fileName = [NSString stringWithFormat:@"%@_%ld.png",[self.urlDict objectForKey:@"paperID"],(long)listView.tag];
                    NSString *pngPath = [self pngFilePath];
                    [UIImagePNGRepresentation(image) writeToFile:pngPath atomically:YES];

                    [dataDict setObject:@"1" forKey:@"userAnswerImage"];
                    [dataDict setObject:fileName forKey:@"user_answer"];
                
                    //答案保存在数据库
                    NSString *qstId = [dataDict objectForKey:@"qstId"];
                    NSString *paperId = [NSString stringWithFormat:@"%@",[_urlDict objectForKey:@"paperID"]];
                    BOOL success;
                    success = [Sqlite updateUserAnswer:fileName  user_right_count:@"1"title_id:qstId paperId:paperId];
                    if (success) {
                        FMSCHBLog(@"保存成功!");
                    }else{
                        FMSCHBLog(@"保存失败!");
                    }
                    success = [Sqlite updateUserAnswerImage:@"1" paperId:paperId title_id:qstId];
                    if (success) {
                        FMSCHBLog(@"userAnswerImage状态保存成功!");
                    }else{
                        FMSCHBLog(@"userAnswerImage状态保存失败!");
                    }
                
                    NSUserDefaults *standard = [NSUserDefaults standardUserDefaults];
                    NSString *paperIDWithName =[NSString stringWithFormat:@"%@_%@",[_urlDict objectForKey:@"paperID"],@"userName"];
                    [standard setObject:@"1" forKey:paperIDWithName];//判断是否做过试题
                    // 更新界面
                    float Version=[[[UIDevice currentDevice] systemVersion] floatValue];
                    HBSimpleTableViewCell *simpleCell = nil;
                    if(Version<8.0)
                    {
                        simpleCell  = (HBSimpleTableViewCell *)btn.superview.superview;
                    }else{
                        simpleCell  = (HBSimpleTableViewCell *)btn.superview;
                    }
                    UIImageView *mageView = (UIImageView *)[simpleCell.draftImageView viewWithTag:100];
                    UIImage *image1 = [UIImage imageWithContentsOfFile:pngPath];
                    [mageView setImage:image1];
        };
        [draft pushToView];
    };
    tableView.listPhotoBlock = ^(HBListTableView *listView,UIButton *btn){
        NSInteger   pageIndex =  swipeView.currentPage;
        NSMutableDictionary *dataDict = [self.paperArray objectAtIndex:pageIndex];
        NSString *user_answer = [dataDict objectForKey:@"user_answer"];
        if ([user_answer isEqualToString:@""]||!user_answer) {
            //删除草稿图片文件
            NSString *strPath = [NSString stringWithFormat:@"%@/image/%@",[self.urlDict objectForKey:@"paperID"],[dataDict objectForKey:@"user_answer"]];//图片路径
            NSString *path0 = [FMPAPERSAVE_PATH stringByAppendingPathComponent:strPath];
            BOOL sucess = [ApplicationUtils deleteExitsFile:path0];
            if (sucess) {
                FMSCHBLog(@"----listPhotoBlock---删除图片成功--------");
            }else{
                FMSCHBLog(@"----listPhotoBlock---删除图片失败--------");
            }
        }
        [self photoBtnClicked:btn];
    };*/
    tableView.tableType = HBListTableViewTypeTest;
    return tableView;
}
- (void)swipeViewCurrentItemIndexDidChange:(SwipeView *)swipeView
{
    if (self.paperArray.count==0) {
        return;
    }
    //更新收藏按钮
    _currentPage =swipeView.currentItemIndex;
    NSMutableDictionary *dataDict = [self.paperArray objectAtIndex:_currentPage];
    NSString *paper_title_ = [dataDict objectForKey:@"paper_title"];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//异步进行
        NSString *paperID =[NSString stringWithFormat:@"%@",[_urlDict objectForKey:@"paperID"]];
        BOOL success = [Sqlite updateCurrentPageFlag:_currentPage paperId:paperID];
        if (success) {
            FMSCHBLog(@"保存进度成功");
        }else{
            FMSCHBLog(@"保存进度失败");
        }
    });
    
//    NSString *qtype = [dataDict objectForKey:@"qtype"];
//    if ([qtype isEqualToString:@"1"]) {
//        qtype = @"(单)";
//    }else if([qtype isEqualToString:@"2"]){
//        qtype = @"(多)";
//    }else if([qtype isEqualToString:@"3"]){
//        qtype = @"(判)";
//    }else if([qtype isEqualToString:@"4"]){
//        qtype = @"(简)";
//    }else{
//        qtype = @"(其他)";
//    }
//    NSString *paperTitleAndCount = [NSString stringWithFormat:@"%@ 共%02ld/%02lu题",paper_title_,currentPage+1,(unsigned long)[self.paperArray count]];
    NSString *paperTitleAndCount = [NSString stringWithFormat:@"%@",paper_title_];
    [titleLabel setText:paperTitleAndCount];
    
    NSString *titleAndCount = [NSString stringWithFormat:@"%02ld/%02lu",_currentPage+1,(unsigned long)[self.paperArray count]];
    [totalLabel setText:titleAndCount];
    
    NSString *favourite_flag = [NSString stringWithFormat:@"%@",[dataDict objectForKey:@"favourite_flag"]];
    BOOL isCollection = NO;
    if ([favourite_flag isEqualToString:@"1"]) {
        isCollection = YES;
    }
    [collectionBtn setSelected:isCollection];

    selectionStr = @"";
    //update page control page
    if (swipeView.currentItemIndex==0&&_currentPage==swipeView.currentItemIndex) {
        [ApplicationUtils makeToast:@"已第一页" withImageName:@"no" withView:self.view];
        return;
    }
    if ([self.paperArray count]-1 == swipeView.currentItemIndex) {
        [ApplicationUtils makeToast:@"已最后一页" withImageName:@"no" withView:self.view];
        return;
    }
}
-(void)swipeViewWillBeginDragging:(SwipeView *)swipeView{
    
}
- (void)swipeViewDidScroll:(SwipeView *)swipeView{
    
}

- (void)swipeView:(SwipeView *)swipeView didSelectItemAtIndex:(NSInteger)index
{
    FMSCHBLog(@"Selected item at index %li", (long)index);
}


#pragma -PaperListViewDelegate
#pragma --
#pragma -
#pragma HBListTableViewDelegate
-(void)HBListTableView:(HBListTableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath userAnswer:(NSString *)userAnswer{
    NSUserDefaults *standard = [NSUserDefaults standardUserDefaults];
    NSString *paperIDWithName =[NSString stringWithFormat:@"%@_%@",[_urlDict objectForKey:@"paperID"],@"userName"];
    [standard setObject:@"1" forKey:paperIDWithName];//判断是否做过试题
    
    NSMutableDictionary *dataDict_user = (NSMutableDictionary *)[self.paperArray objectAtIndex:_currentPage];
//    NSString *title_id = [NSString stringWithFormat:@"%ld",currentPage+1.0];
    NSString *qstId = [dataDict_user objectForKey:@"tq_id"];
    NSString *qtype = [dataDict_user objectForKey:@"qtype"];
    if ([qtype isEqualToString:@"1"]||[qtype isEqualToString:@"3"]||[qtype isEqualToString:@"0"]) {//0是简单题
//        if (!isExercise) {
            [dataDict_user setObject:userAnswer forKey:@"user_answer"];
            [self.paperArray replaceObjectAtIndex:_currentPage withObject:dataDict_user];//保存内存中的数组，以便返回上页时出现没有选择情况
//        }
        NSMutableDictionary *dataDict = (NSMutableDictionary *)[self.paperArray objectAtIndex:_currentPage];
        noSelected = 0;
        NSString *answer = [dataDict objectForKey:@"answer"];
        FMSCHBLog(@"answer-------%@",answer);
        NSRange range;
        range.location =0;
        range.length =answer.length;
        answer = [answer substringWithRange:range];
        FMSCHBLog(@"answer---substringWithRange----%@",answer);
        selectionStr = userAnswer;
        NSString *paperId = [NSString stringWithFormat:@"%@",[_urlDict objectForKey:@"paperID"]];
        if (isExercise) {

        }else{//测试
            BOOL success;
            NSString *score = [dataDict_user objectForKey:@"score"];
            if([selectionStr isEqualToString:answer]){
                success = [Sqlite updateUserAnswer:selectionStr  user_right_count:@"1"title_id:qstId paperId:paperId];
                if (success) {
                    FMSCHBLog(@"保存成功!");
                    Sum = Sum+1*[score intValue];
                }else{
                    FMSCHBLog(@"保存失败!");
                }
            }else{
                success = [Sqlite updateUserAnswer:selectionStr user_right_count:@"0"title_id:qstId paperId:paperId];
                if (success) {
                    FMSCHBLog(@"保存成功!");
                }else{
                    FMSCHBLog(@"保存失败!");
                }
            }
            
#pragma mark 禁止点击翻页
//            [_swipeView scrollToPage:_currentPage+1 duration:0.3];
        }
    }else if([qtype isEqualToString:@"2"]){// 2

        noSelected = 0;
        NSDictionary *dataDict = [self.paperArray objectAtIndex:_currentPage];
        NSString *answer = [dataDict objectForKey:@"answer"];
        selectionStr = userAnswer;
        NSMutableArray *answerArr = [NSMutableArray arrayWithCapacity:1];
        if (!isExercise) {//当为练习模式时，不需要记录答案
            NSString *anwerStr = [dataDict objectForKey:@"user_answer"];
            for (int i = 0; i < [anwerStr length]; i++) {
                NSString *charStr = [NSString stringWithFormat:@"%C", [anwerStr characterAtIndex:i]];
                if ([charStr isEqualToString:@"("]||[charStr isEqualToString:@")"]||[charStr isEqualToString:@"n"]||[charStr isEqualToString:@"u"]||[charStr isEqualToString:@"l"]) {
                    
                }else{
                    [answerArr addObject:charStr];//避免出现当继续考试时出现的选项选择的不正确问题
                }
            }
        }
        if (!self.answerArray) {
            self.answerArray = [NSMutableArray arrayWithCapacity:1.0];
        }
        [self.answerArray setArray:answerArr];
        if (![self.answerArray containsObject:selectionStr]) {
            [self.answerArray addObject:selectionStr];
        }else{
            [self.answerArray removeObject:selectionStr];
        }
        [self.answerArray  sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];//升序
        NSMutableString *outputAfter = [[NSMutableString alloc] init];
        for(NSString *str in self.answerArray){
            //            [outputAfter appendFormat:@"%@、",str];
            [outputAfter appendFormat:@"%@",str];//1、	多选题即便是选择对了，也会判断该题错误。练习模式下是对的
        }
        FMSCHBLog(@"排序后:%@",outputAfter);
        if (isExercise) {

        }else{//测试
            if (answer.length>7) {
                NSRange range;
                range.length = answer.length-7;
                range.location = 3;
                answer = [answer substringWithRange:range];
            }
            NSString *paperId = [NSString stringWithFormat:@"%@",[_urlDict objectForKey:@"paperID"]];
            if (outputAfter.length>0) {
                //            ans = [outputAfter substringToIndex:outputAfter.length];//截取后的字符串
                //            //多选设置答案
                NSMutableDictionary *dataDict_user = (NSMutableDictionary *)[self.paperArray objectAtIndex:_currentPage];
                [dataDict_user setObject:outputAfter forKey:@"user_answer"];
                [self.paperArray replaceObjectAtIndex:_currentPage withObject:dataDict_user];//保存内存中的数组，以便返回上页时出现没有选择情况
                BOOL success;
                NSString *score = [dataDict_user objectForKey:@"score"];
                if ([outputAfter isEqualToString:answer]) {
                    success = [Sqlite updateUserAnswer:outputAfter user_right_count:@"1" title_id:qstId paperId:paperId];
                    if (success) {
                        FMSCHBLog(@"保存成功!");
                        Sum = Sum+1*[score intValue];
                    }else{
                        FMSCHBLog(@"保存失败!");
                    }
                }else{
                    success = [Sqlite updateUserAnswer:outputAfter user_right_count:@"0"title_id:qstId paperId:paperId];
                    if (success) {
                        FMSCHBLog(@"保存成功!");
                    }else{
                        FMSCHBLog(@"保存失败!");
                    }
                }
            }
        }
    }else{    }
}
-(void)HBListTableView:(HBListTableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath userAnswer:(NSString *)userAnswer WithDict:(NSMutableDictionary *)dataDict{//简单题的多项选择
    //简答题中的选择题
    NSString *answer = [dataDict objectForKey:@"answer"];
    NSString *tqId = [dataDict objectForKey:@"tq_id"];
    NSString *parent_id = [dataDict objectForKey:@"parent_id"];
    NSString *user_answer = [dataDict objectForKey:@"user_answer"];
    selectionStr = userAnswer;
    NSMutableArray *answerArr = [NSMutableArray arrayWithCapacity:1];
    if (!isExercise) {//当为练习模式时，不需要记录答案
        NSString *anwerStr = user_answer;
        for (int i = 0; i < [anwerStr length]; i++) {
            NSString *charStr = [NSString stringWithFormat:@"%C", [anwerStr characterAtIndex:i]];
            if ([charStr isEqualToString:@"("]||[charStr isEqualToString:@")"]||[charStr isEqualToString:@"n"]||[charStr isEqualToString:@"u"]||[charStr isEqualToString:@"l"]) {
                
            }else{
                [answerArr addObject:charStr];//避免出现当继续考试时出现的选项选择的不正确问题
            }
        }
    }
    if (!self.answerArray) {
        self.answerArray = [NSMutableArray arrayWithCapacity:1.0];
    }
    [self.answerArray setArray:answerArr];
    if (![self.answerArray containsObject:selectionStr]) {
        [self.answerArray addObject:selectionStr];
    }else{
        [self.answerArray removeObject:selectionStr];
    }
    [self.answerArray  sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];//升序
    NSMutableString *outputAfter = [[NSMutableString alloc] init];
    for(NSString *str in self.answerArray){
        //            [outputAfter appendFormat:@"%@、",str];
        [outputAfter appendFormat:@"%@",str];//1、	多选题即便是选择对了，也会判断该题错误。练习模式下是对的
    }
    FMSCHBLog(@"排序后:%@",outputAfter);
    if (isExercise) {
        
    }else{//测试
        NSString *paperId = [NSString stringWithFormat:@"%@",[_urlDict objectForKey:@"paperID"]];
        if (outputAfter.length>0) {
            //            ans = [outputAfter substringToIndex:outputAfter.length];//截取后的字符串
            //            //多选设置答案
            //                NSMutableDictionary *dataDict_user = (NSMutableDictionary *)[self.paperArray objectAtIndex:currentPage];
            [dataDict setObject:outputAfter forKey:@"user_answer"];
            //                [self.paperArray replaceObjectAtIndex:currentPage withObject:dataDict_user];//保存内存中的数组，以便返回上页时出现没有选择情况
            BOOL success;
            NSString *score = [dataDict objectForKey:@"score"];
            if ([outputAfter isEqualToString:answer]) {
                success = [Sqlite updateSimpleSingleUserAnswer:outputAfter user_right_count:@"1" tqId:tqId paperId:paperId parentid:parent_id];
                if (success) {
                    FMSCHBLog(@"保存成功!");
                    Sum = Sum+1*[score intValue];
                }else{
                    FMSCHBLog(@"保存失败!");
                }
            }else{
                success = [Sqlite updateSimpleSingleUserAnswer:outputAfter user_right_count:@"0" tqId:tqId paperId:paperId parentid:parent_id];
                if (success) {
                    FMSCHBLog(@"保存成功!");
                }else{
                    FMSCHBLog(@"保存失败!");
                }
            }
        }
    }
}
/*
-(void)selectBtnClicked:(ISMutileButton *)sender{
    NSUserDefaults *standard = [NSUserDefaults standardUserDefaults];
    NSString *paperIDWithName =[NSString stringWithFormat:@"%@_%@",[_urlDict objectForKey:@"paperID"],@"userName"];
    [standard setObject:@"1" forKey:paperIDWithName];//判断是否做过试题
    NSString *title_id = [NSString stringWithFormat:@"%ld",currentPage+1];
    if (sender.isMultile) {//单选
        NSMutableDictionary *dataDict_user = (NSMutableDictionary *)[self.paperArray objectAtIndex:currentPage];
        XingAndLabel_UIView  *titleLableView_ = (XingAndLabel_UIView *)sender.superview;
        NSString *optionsStr_ =titleLableView_.titleLabel.text;
        NSString *selectionStr_ = [[optionsStr_ componentsSeparatedByString:@"."] objectAtIndex:0];
        if (!isExercise) {
            [dataDict_user setObject:selectionStr_ forKey:@"user_answer"];
            [self.paperArray replaceObjectAtIndex:currentPage withObject:dataDict_user];//保存内存中的数组，以便返回上页时出现没有选择情况
        }
        NSMutableDictionary *dataDict = (NSMutableDictionary *)[self.paperArray objectAtIndex:currentPage];
        noSelected = 0;
        NSString *answer = [dataDict objectForKey:@"answer"];
        FMSCHBLog(@"answer-------%@",answer);
        NSRange range;
        if (answer.length>3) {
            range.location =3;
            range.length =1;
        }else{
            range.location =0;
            range.length =answer.length;
        }
        answer = [answer substringWithRange:range];
        FMSCHBLog(@"answer---substringWithRange----%@",answer);
        XingAndLabel_UIView  *titleLableView = (XingAndLabel_UIView *)sender.superview;
        NSString *optionsStr =titleLableView.titleLabel.text;
        selectionStr = [[optionsStr componentsSeparatedByString:@"."] objectAtIndex:0];
        NSString *paperId = [NSString stringWithFormat:@"%@",[_urlDict objectForKey:@"paperID"]];
        if (isExercise) {

        }else{//测试
            BOOL success;
            NSString *score = [dataDict_user objectForKey:@"score"];
            if([selectionStr isEqualToString:answer]){
                success = [Sqlite updateUserAnswer:selectionStr user_error_count:@"0" user_right_count:@"1"title_id:title_id paperId:paperId];
                if (success) {
                    FMSCHBLog(@"保存成功!");
                    Sum = Sum+1*[score intValue];
                }else{
                    FMSCHBLog(@"保存失败!");
                }
            }else{
                success = [Sqlite updateUserAnswer:selectionStr user_error_count:@"1" user_right_count:@"0"title_id:title_id paperId:paperId];
                if (success) {
                    FMSCHBLog(@"保存成功!");
                }else{
                    FMSCHBLog(@"保存失败!");
                }
            }
            [_swipeView scrollToPage:currentPage+1 duration:0.3];
        }
    }else{
        noSelected = 0;
        NSDictionary *dataDict = [self.paperArray objectAtIndex:currentPage];
        NSString *answer = [dataDict objectForKey:@"answer"];
        XingAndLabel_UIView  *titleLableView = (XingAndLabel_UIView *)sender.superview;
        NSString *optionsStr =titleLableView.titleLabel.text;
        FMSCHBLog(@"optionsStr==%@",optionsStr);
        selectionStr = [[optionsStr componentsSeparatedByString:@"."] objectAtIndex:0];
        NSMutableArray *answerArr = [NSMutableArray arrayWithCapacity:1];
        if (!isExercise) {//当为练习模式时，不需要记录答案
            NSString *anwerStr = [dataDict objectForKey:@"user_answer"];
            for (int i = 0; i < [anwerStr length]; i++) {
                NSString *charStr = [NSString stringWithFormat:@"%C", [anwerStr characterAtIndex:i]];
                if ([charStr isEqualToString:@"("]||[charStr isEqualToString:@")"]||[charStr isEqualToString:@"n"]||[charStr isEqualToString:@"u"]||[charStr isEqualToString:@"l"]) {
                    
                }else{
                    [answerArr addObject:charStr];//避免出现当继续考试时出现的选项选择的不正确问题
                }
            }
        }
        if (!self.answerArray) {
            self.answerArray = [NSMutableArray arrayWithCapacity:1.0];
        }
        [self.answerArray setArray:answerArr];
        if (![self.answerArray containsObject:selectionStr]) {
            [self.answerArray addObject:selectionStr];
        }else{
            [self.answerArray removeObject:selectionStr];
        }
        [self.answerArray  sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];//升序
        NSMutableString *outputAfter = [[NSMutableString alloc] init];
        for(NSString *str in self.answerArray){
            //            [outputAfter appendFormat:@"%@.",str];
            [outputAfter appendFormat:@"%@",str];//1、	多选题即便是选择对了，也会判断该题错误。练习模式下是对的
        }
        FMSCHBLog(@"排序后:%@",outputAfter);
        if (isExercise) {

        }else{//测试
            if (answer.length>7) {
                NSRange range;
                range.length = answer.length-7;
                range.location = 3;
                answer = [answer substringWithRange:range];
            }
            NSString *paperId = [NSString stringWithFormat:@"%@",[_urlDict objectForKey:@"paperID"]];
            if (outputAfter.length>0) {
                //            ans = [outputAfter substringToIndex:outputAfter.length];//截取后的字符串
                //            //多选设置答案
                NSMutableDictionary *dataDict_user = (NSMutableDictionary *)[self.paperArray objectAtIndex:currentPage];
                [dataDict_user setObject:outputAfter forKey:@"user_answer"];
                [self.paperArray replaceObjectAtIndex:currentPage withObject:dataDict_user];//保存内存中的数组，以便返回上页时出现没有选择情况
                BOOL success;
                NSString *score = [dataDict_user objectForKey:@"score"];
                if ([outputAfter isEqualToString:answer]) {
                    success = [Sqlite updateUserAnswer:outputAfter user_error_count:@"0" user_right_count:@"1" title_id:title_id paperId:paperId];
                    if (success) {
                        FMSCHBLog(@"保存成功!");
                        Sum = Sum+1*[score intValue];
                    }else{
                        FMSCHBLog(@"保存失败!");
                    }
                }else{
                    success = [Sqlite updateUserAnswer:outputAfter user_error_count:@"1" user_right_count:@"0"title_id:title_id paperId:paperId];
                    if (success) {
                        FMSCHBLog(@"保存成功!");
                    }else{
                        FMSCHBLog(@"保存失败!");
                    }
                }
            }
        }
    }
}*/
-(void)webViewDidFinishLoad:(UIWebView *)webView{
    
}
-(void)releaseMyDealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
    headerBg = nil;
    titleLabel = nil;
    for (UIView *subView in [_swipeView subviews]) {
        [subView removeFromSuperview];
    }
    if (_swipeView) {
        [_swipeView removeFromSuperview];
        _swipeView = nil;
    }
    self.answerArray = nil;
    collectionBtn = nil;
    selectionStr = nil;
    paper_title = nil;
    paper_score = nil;
    paper_time = nil;
    _user_time = nil;
    if (self.paperArray) {
        [self.paperArray removeAllObjects];
        self.paperArray = nil;
    }
    self.urlDict = nil;
    self.answerBtn = nil;
    //清除UIWebView的缓存
    [[NSURLCache  sharedURLCache ] removeAllCachedResponses];
}
-(void)dealloc{
    [self releaseMyDealloc];
}
- (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) orient
{
    return((supportedOrientationsMask >> orient) & 1);
}
- (BOOL)shouldAutorotate{
    return((supportedOrientationsMask >> self.interfaceOrientation) & 1);
}
- (NSUInteger)supportedInterfaceOrientations{
    return supportedOrientationsMask;
}
-(void)setCurrentPage:(NSInteger)currentPage{
    if (_currentPage!=currentPage) {
        _currentPage=currentPage;
    }
}
@end
